package cn.wolfcode.crm.util;

import com.alibaba.fastjson.JSON;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

public class MyFormAuthenticationFilter extends FormAuthenticationFilter {
    //解决重复登录的问题,在登录前将用户注销掉

//    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
//        //1.通过shiro的安全工具拿到当前登录的用户
//        Subject subject = SecurityUtils.getSubject();
//        //2.如果用户为已验证状态,则执行注销操作
//        if(subject.isAuthenticated()){
//            subject.logout();
//        }
//        return super.onAccessDenied(request, response);
//    }

    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (isLoginRequest(request, response)) {
            //1.通过shiro的安全工具拿到当前登录的用户
            Subject subject = SecurityUtils.getSubject();
            //2.如果用户为已验证状态,则执行注销操作
            if (subject.isAuthenticated())

            {
                subject.logout();
            }
        }

        return super.isAccessAllowed(request, response, mappedValue);

    }

    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        response.getWriter().print(JSON.toJSONString(new JSONResult()));
        return false;
    }

    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        String errorMsg = "登录异常,请联系管理员";
        if (e != null) {
            if (e instanceof UnknownAccountException) {
                errorMsg = "用户名不存在";
            } else if (e instanceof CredentialsException) {
                errorMsg = "密码错误";
            }
        }
        try {
            response.getWriter().print(JSON.toJSONString(JSONResult.mark(errorMsg)));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        e.printStackTrace();
        return false;
    }

}
